package com.xueshandai.db.migration.persistence.implement;

import com.xueshandai.db.migration.mode.LineData;
import com.xueshandai.db.migration.persistence.Access;
import org.apache.log4j.Logger;

import java.io.*;

/**
 * Created by Zetas on 2014/12/25.
 */
public class AccessFileImpl implements Access {

    private File file;
    private FileWriter fileWriter;
    private BufferedWriter bufferedWriter;
    private FileReader fileReader;
    private BufferedReader bufferedReader;
    private String tempLine;

    public AccessFileImpl(File file) {
        this.file = file;
        try {
            this.fileWriter = new FileWriter(this.file, true);
            this.fileReader = new FileReader(this.file);
        } catch (IOException e) {
            logger.error("构造AccessFileImpl对象失败，文件为："+file.getAbsolutePath(), e);
        }
        this.bufferedWriter = new BufferedWriter(fileWriter);
        this.bufferedReader = new BufferedReader(fileReader);
        this.tempLine = null;
        logger.info("构造AccessFileImpl对象成功，文件为："+file.getAbsolutePath());
    }

    @Override
    public boolean next() {
        try {
            tempLine = bufferedReader.readLine();
        } catch (IOException e) {
            logger.error(e);
        } finally {
            if ( tempLine == null ) {
                return false;
            } else {
                return true;
            }
        }
    }

    @Override
    public LineData readLine() {
        String temp = tempLine;
        tempLine = null;
        return LineData.parse(temp);
    }

    @Override
    public void writeLine(LineData lineData) {
        String line = lineData.toJSON();
        try {
            bufferedWriter.write(line, 0, line.length());
            bufferedWriter.newLine();
            bufferedWriter.flush();
        } catch (IOException e) {
            logger.error("写入文件失败："+line, e);
        }
    }

    @Override
    public void destroy() {
        if ( bufferedWriter != null ) try {
            bufferedWriter.close();
        } catch (IOException e) {
            logger.error("释放资源失败：", e);
        }
        if ( fileWriter != null ) try {
            fileWriter.close();
        } catch (IOException e) {
            logger.error("释放资源失败", e);
        }
        if ( bufferedReader != null ) try {
            bufferedReader.close();
        } catch (IOException e) {
            logger.error("释放资源失败", e);
        }
        if ( fileReader != null ) try {
            fileReader.close();
        } catch (IOException e) {
            logger.error("释放资源失败：", e);
        }
    }
}
